//
//  WithdrawViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/22.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "WithdrawViewController.h"
#import "RechargeListViewController.h"
#import "TransformRecordVC.h"
#import "WithdrawCell.h"
#import "WithdrawViewModel.h"
#import "NoDataView.h"

@interface WithdrawViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong) WithdrawViewModel *viewModel;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *subMitBtn;

@property (nonatomic, strong) WithdrawCell *cell;
@property (nonatomic, strong) NoDataView *noDataView;

/** ETH现价 */
@property (nonatomic, copy) NSString *ETHPrice;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *rightListButton;

@end

@implementation WithdrawViewController

#pragma mark - VC Life

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.tintAdjustmentMode = UIViewTintAdjustmentModeNormal;
}

- (void)viewDidLoad {  
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.subMitBtn];
    
    self.navigationItem.title = kLocalizedString(@"划转", nil);
    [self.rightListButton setTitle:kLocalizedString(@"划转记录", nil)];

    [self startLoading];
    [self inputAction];
    [self outPutAction];
    
    //获取用户提现手续费
    [self.viewModel.drawRate  execute:nil];
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tableViewGesture];
}

- (IBAction)rightBarButtonAction:(UIBarButtonItem *)sender {
    TransformRecordVC *vc = [[TransformRecordVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableViewTouchInSide
{
    [self.view endEditing:YES];
}

#pragma mark - Input
- (void)inputAction
{
    @weak(self)
    //提现
    [[self.subMitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_ startClearBgColorLoading];
        [self_weak_.view endEditing:YES];
        [self_weak_.viewModel.withdrawCommand  execute:@{@"walleatAdress":@"",@"value":self_weak_.cell.cbtNameTextField.text}];
    }];
}

#pragma mark - OutPut
- (void)outPutAction
{
    @weak(self)
    //获取提现手续费成功
    [self.viewModel.drawRate.executionSignals.switchToLatest subscribeNext:^(NSDictionary *dic) {
        [self_weak_ stopLoading];
        self_weak_.ETHPrice = dic[@"ETHPrice"];
        [self_weak_.noDataView removeFromSuperview];
        self_weak_.cell.cbtInfoLabel.text = @"";
    }];
    
    //获取提现手续费失败
    [self.viewModel.drawRate.errors subscribeNext:^(NSError * _Nullable x) {
        [self_weak_ stopLoading];
        [self_weak_.view addSubview:self_weak_.noDataView];
    }];
    
    //提现成功
    [self.viewModel.withdrawCommand.executionSignals.switchToLatest subscribeNext:^(NSString *x) {
        if (![x isEqualToString:@"-1"]) {
            [[CBTLocalUserManager sharedInstance]refreshUserInfoDic:@{@"asset": x}];
            if (self_weak_.WithdrawFinishBlock != nil) {
                self_weak_.WithdrawFinishBlock(x);
            }
        }
        [self_weak_.navigationController popViewControllerAnimated:YES];
    }];
    
    //提现失败
    [self.viewModel.withdrawCommand.errors subscribeNext:^(NSError *x) {
        [self_weak_ stopLoading];
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weak(self)
    _cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    _cell.cbtNameTextField.delegate = self;
    [_cell setAllBtnClickBlock:^(NSString *userAsset){
        self_weak_.cell.ethLabel.text = [NSString stringWithFormat:@"≈%@ ETH",[NSString decimalDivisionWithNum:[NSString stringWithFormat:@"%@",userAsset] num1:[NSString stringWithFormat:@"%@",self_weak_.ETHPrice] decimals:4]];
    }];
    return _cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 241;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSMutableString *s = [NSMutableString stringWithFormat:@"%@",textField.text];
    [s insertString:string atIndex:range.location];
    if ([s SizeCount] > 2 || ([s isEqualToString:@"."] && [NSString isBlankString:textField.text])) {
        return NO;
    }
    if (![NSString validateNumber:string]) {
        return NO;
    }
    if ([textField.text containsString:@"."] && [string isEqualToString:@"."]) {
        return NO;
    }
    
    if ((![[NSString stringWithFormat:@"%@",s] containsString:@"."] && textField.text.length >= 7 && ![string isEqualToString:@""]) || string.length > 10) {
        return NO;
    }
    _cell.ethLabel.text = [NSString stringWithFormat:@"≈%@ ETH",[NSString decimalDivisionWithNum:[NSString stringWithFormat:@"%@",s] num1:[NSString stringWithFormat:@"%@",self.ETHPrice] decimals:4]];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    self.cell.ethLabel.text = @"≈0 ETH";
    return YES;
}

#pragma mark - Lazy

- (NoDataView *)noDataView
{
    if (!_noDataView) {
        @weak(self)
        _noDataView = [[NoDataView alloc]initWithFrame:self.view.bounds type:(ShowType_NoNetWork) clickBlock:^{
            [self_weak_ startClearBgColorLoading];
            [self_weak_.viewModel.drawRate  execute:nil];
        }];
    }
    return _noDataView;
}

- (WithdrawViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[WithdrawViewModel alloc]init];
        _viewModel.viewControllers = self;
    }
    return _viewModel;
}

- (UIButton *)subMitBtn
{
    if (!_subMitBtn) {
        _subMitBtn = [[UIButton alloc]initWithFrame:CGRectMake(25, 241, ScreenNarrowSide - 50, 40)];
        [_subMitBtn setTitle:kLocalizedString(@"确认", nil) forState:(UIControlStateNormal)];
        [_subMitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
       
        _subMitBtn.backgroundColor     = DefaultOrangeColor;
        _subMitBtn.layer.cornerRadius  = 20;
        _subMitBtn.layer.masksToBounds = YES;
        _subMitBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    return _subMitBtn;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenNarrowSide, ScreenWideSide - self.tabBarController.tabBar.bounds.size.height - 15) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle  = UITableViewCellEditingStyleNone;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        _tableView.delegate   = self;
        _tableView.dataSource = self;
        
        if (@available(iOS 11.0, *)){
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight           = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        
        [_tableView registerClass:[WithdrawCell class] forCellReuseIdentifier:@"Cell"];
        
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}


@end
